Getting Safari’s Selection on iPad As HTML With A JavaScript Bookmarklet

I modified this bookmarklet posted by “Tim Down” on StackOverflow to send selected text from Safari to Drafts as HTML. The result is the following code:

javascript:(function(){var%20h="",s,g,c,i;if(window.getSelection){s=window.getSelection();if(s.rangeCount){c=document.createElement("div");for(i=0;i<s.rangeCount;++i){c.appendChild(s.getRangeAt(i).cloneContents());}h=c.innerHTML}}else%20if((s=document.selection)&&s.type=="Text"){h=s.createRange().htmlText;}window.location='drafts://x-callback-url/create?text='+(h);})()

So let’s say you want to grab the first paragraph in this post. Normally, in Safari for iPad you’d end up with the plain text fetched by window.getSelection:

This is a fantastic report with lots of data points for any developer trying to get their apps featured by Apple. Dave Addey’s highly interactive regional graphs and notes are very well done. Be sure to check out Dave Addey’s other works on his main blog.

As you can see, formatting and hyperlinks have been removed. With the bookmarklet above, you’ll receive the HTML version of the selection – which looks like this. But what’s the point?

My idea was that I wanted to be able to automate the process of capturing rich text from iOS’ Safari; I wanted to achieve the same kind of functionality I have on the Mac, where rich text can be dragged from Safari or Chrome and dropped into Evernote, preserving styles, hyperlinks, and images. I thought that combining HTML output with an Evernote Append action (with the “Send as Markdown HTML” option turned on) would let me receive valid HTML content in Evernote starting from an iOS workflow. And, for the most part, I was right, because the workflow does mostly work.

As it turns out, Evernote is extremely cautious with the HTML tags they accept, and the ones that are supported follow the XHTML guidelines as ENML is a superset of XHTML. This means that my bookmarklet will work for something as simple as selecting a single paragraph, but may easily fail with multiple selections, inline images, complex styles, and so forth. When that will happen, Drafts will return an error when trying to append HTML to Evernote; obviously, this will work just fine with Dropbox, which doesn’t care about the kind of text you’re using in your actions. Even better, this should work very well with Textastic’s just-released update that supports x-callback-url.

I guess the solution would be to build a Pythonista-based converter for Evernote-approved XHTML tags and place it between Safari and Drafts, converting HTML tags Evernote won’t like to compatible ones. If you’re interested, my birthday is August 10.

→ Source: stackoverflow.com